package assg.funnycells.server;

import java.net.*;

import assg.funnycells.util.*;

public class Server {
    ServerSocket serverSoc;
    ServerState serverState;
    Configuration config;
    Logger logger;
    int port;
    ActivityDisplay display;
    
    public Server(ActivityDisplay display) throws Exception {
	this.display = display;
	config = Coordinator.getConfig();
	port = config.getIntVal(Configuration.SERVER, Configuration.PORT);
	serverSoc = new ServerSocket(port);
	serverState = new ServerState(display);
	logger = Logger.getDefaultLogger();
    }

    public ServerState serverState() {
	return serverState;
    }

    public void start() throws Exception {
	Socket soc;
	int numerrors = 0;
	while(true) {
	    try {
		soc = serverSoc.accept();
		logger.info("Got new connection");
		Cell cell = new Cell(soc, serverState, display);
	    } catch(Exception e) {
		numerrors++;
		if(numerrors > 3)
		    throw e;
	    }
	}
    }
    
}